package login;


import beans.UserSession;

import com.ams.model.AM.AMSAppModuleImpl;

import java.text.ParseException;
import java.text.SimpleDateFormat;

import java.util.List;

import javax.el.ExpressionFactory;

import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import javax.servlet.http.HttpSession;

import javax.xml.ws.WebServiceRef;

import oracle.adf.model.binding.DCBindingContainer;
import oracle.adf.model.binding.DCDataControl;

import utils.ADFUtils;
import utils.JSFUtils;
/*
import ws.MirrorDataService;
import ws.MirrorDataServiceSoap;
import ws.types.ArrayOfBOEmployee;
import ws.types.BOEmployee;
import ws.types.BOUserLogin;
import ws.types.GetX0020TheX0020DetailsX0020OfX0020Employee;
import ws.types.GetX0020TheX0020DetailsX0020OfX0020EmployeeResponse;
import ws.types.GetX0020UserX0020DetailsX0020FromX0020SessionX0020KeyResponse;
import ws.types.ServiceAuthenticationHeader;
*/
/*
import wsad.MirrorDataService;
import wsad.MirrorDataServiceSoap;
import wsad.types.ArrayOfBOEmployee;
import wsad.types.BOEmployee;
import wsad.types.BOUserLogin;
import wsad.types.GetX0020TheX0020DetailsX0020OfX0020Employee;
import wsad.types.GetX0020TheX0020DetailsX0020OfX0020EmployeeResponse;
import wsad.types.GetX0020UserX0020DetailsX0020FromX0020SessionX0020KeyResponse;
import wsad.types.ServiceAuthenticationHeader;
*/


public class RoleFinder {
    static UserSession session = new UserSession();
   
    @WebServiceRef
    private static wsad.MirrorDataService mirrorDataService;
    
    @WebServiceRef
    private static ws.MirrorDataService mirrorDataServiceDev;
    
    private final String serviceAuthenticationHeaderUser =
        "MirrorServiceClient";
    private final String serviceAuthenticationHeaderPasswod = "M!rr0rClient";

    public RoleFinder() {
        super();
    }
//for AD login
    public String roleManipulator(wsad.types.GetX0020UserX0020DetailsX0020FromX0020SessionX0020KeyResponse skres) throws ParseException {
     
        mirrorDataService = new wsad.MirrorDataService();
        wsad.MirrorDataServiceSoap mirrorDataServiceSoap =
            mirrorDataService.getMirrorDataServiceSoap();

        wsad.types.ServiceAuthenticationHeader serviceAuthenticationHeader =
            new wsad.types.ServiceAuthenticationHeader();
        serviceAuthenticationHeader.setUserName(serviceAuthenticationHeaderUser);
        serviceAuthenticationHeader.setPassword(serviceAuthenticationHeaderPasswod);    

        wsad.types.GetX0020TheX0020DetailsX0020OfX0020Employee empInput =
            new wsad.types.GetX0020TheX0020DetailsX0020OfX0020Employee();
        wsad.types.GetX0020TheX0020DetailsX0020OfX0020EmployeeResponse empResponse =
            new wsad.types.GetX0020TheX0020DetailsX0020OfX0020EmployeeResponse();
        wsad.types.BOUserLogin user =
            skres.getGetX0020UserX0020DetailsX0020FromX0020SessionX0020KeyResult();
        int empId = user.getEmployeeID();
        empInput.setEmpId(empId);
        empResponse =
                mirrorDataServiceSoap.getEmployeeDetails(empInput, serviceAuthenticationHeader);
       wsad.types. ArrayOfBOEmployee userDetails =
            empResponse.getGetX0020TheX0020DetailsX0020OfX0020EmployeeResult();
        List<wsad.types.BOEmployee> empList = userDetails.getBOEmployee();
        String empCode = null;
        String Role;
        String adminrole;
//        //System.out.println("Checking if the Employee is active");
        for (wsad.types.BOEmployee i : empList) {
            empCode = i.getEmployeeCode();
            System.out.println("\nEmp code:  "+ i.getEmployeeCode()+"\n\n");
//            //System.out.println("\nEmp actibe ??:  "+i.isIsActive());
            if (i.isIsActive()) {
               // adminrole=checkIfAdmin(empCode);
                //Role = retrieveRole(empCode);
//                if (Role == null) {
//                    Role = "emp";
//                    
//                }
              //  System.out.println("\n\n\nAdmin Role:"+adminrole+"\n\n\n");
//                if(adminrole==null){
//                    adminrole="0";
//                }
               
                createSession(i, user);
//                //System.out.println("Im active");
//                if(Role.equals("DHBUH")){
//                    Role="BUH";
//                }
//                return Role;
//            } else {
//                Role = "inActive";
////                //System.out.println("Im inactive");
//                return Role;
//            }
            }
        }

        return "Active";
  
    }


//for Mirror Dev login
    public String roleManipulator(ws.types.GetX0020UserX0020DetailsX0020FromX0020SessionX0020KeyResponse skres) throws ParseException {
       String adLogin= ADFUtils.getResourceBundleValue("com.ams.model.amsmodel.CustomBundle",
                                                                "adLogin");
      
           mirrorDataServiceDev = new ws.MirrorDataService();
           ws.MirrorDataServiceSoap mirrorDataServiceSoap =
               mirrorDataServiceDev.getMirrorDataServiceSoap();

           ws.types.ServiceAuthenticationHeader serviceAuthenticationHeader =
               new ws.types.ServiceAuthenticationHeader();
           serviceAuthenticationHeader.setUserName(serviceAuthenticationHeaderUser);
           serviceAuthenticationHeader.setPassword(serviceAuthenticationHeaderPasswod);

           ws.types.GetX0020TheX0020DetailsX0020OfX0020Employee empInput =
               new ws.types.GetX0020TheX0020DetailsX0020OfX0020Employee();
           ws.types.GetX0020TheX0020DetailsX0020OfX0020EmployeeResponse empResponse =
               new ws.types.GetX0020TheX0020DetailsX0020OfX0020EmployeeResponse();
           ws.types.BOUserLogin user =
               skres.getGetX0020UserX0020DetailsX0020FromX0020SessionX0020KeyResult();
           int empId = user.getEmployeeID();
           empInput.setEmpId(empId);
           empResponse =
                   mirrorDataServiceSoap.getEmployeeDetails(empInput, serviceAuthenticationHeader);
           ws.types.ArrayOfBOEmployee userDetails =
               empResponse.getGetX0020TheX0020DetailsX0020OfX0020EmployeeResult();
           List<ws.types.BOEmployee> empList = userDetails.getBOEmployee();
           String empCode = null;
           String Role;
           String adminrole;
           //        //System.out.println("Checking if the Employee is active");
           for (ws.types.BOEmployee i : empList) {
               empCode = i.getEmployeeCode();
               System.out.println("\nEmp code:  "+ i.getEmployeeCode()+"\n\n");
           //            //System.out.println("\nEmp actibe ??:  "+i.isIsActive());
               if (i.isIsActive()) {
                   adminrole=checkIfAdmin(empCode);
                   Role = retrieveRole(empCode);
                   if (Role == null) {
                       Role = "emp";
                       
                   }
                   System.out.println("\n\n\nAdmin Role:"+adminrole+"\n\n\n");
                   if(adminrole==null){
                       adminrole="0";
                   }
                  
                   createSession(i, user);
           //                //System.out.println("Im active");
                   if(Role.equals("DHBUH")){
                       Role="BUH";
                   }
                   return Role;
               } else {
                   Role = "inActive";
           //                //System.out.println("Im inactive");
                   return Role;
               }

           }

           return "inActive";
       
    }
    
    
    
    
    public static DCBindingContainer getBindingContainer() {
        FacesContext fctx = FacesContext.getCurrentInstance();
        ExpressionFactory exp = fctx.getApplication().getExpressionFactory();
        return (DCBindingContainer)exp.createValueExpression(fctx.getELContext(),
                                                             "#{bindings}",
                                                             DCBindingContainer.class).getValue(fctx.getELContext());
    }

    public String retrieveRole(String empCode) {
        DCBindingContainer bc = getBindingContainer();
        DCDataControl appModuleAMDC;
        appModuleAMDC = bc.findDataControl("SMAppModuleDataControl");
        AMSAppModuleImpl appModuleAM =
            (AMSAppModuleImpl)appModuleAMDC.getApplicationModule();
       //String Role = appModuleAM.initRoleAtLogin(empCode);
//        //System.out.println("ROLE=" + Role);
        //return Role;
        return null;
    }
    public String checkIfAdmin(String empCode) {
//        DCBindingContainer bc = getBindingContainer();
//        DCDataControl appModuleAMDC1;
//        appModuleAMDC1 = bc.findDataControl("SMAppModuleDataControl");
//    
//        AMSAppModuleImpl appModuleAM1 =
//            (AMSAppModuleImpl)appModuleAMDC1.getApplicationModule();
//        String Adminrole = appModuleAM1.initAdminRole(empCode);
//            //System.out.println("ROLE=" + Role);
     //   return Adminrole;
        return null;
    }
    
    
    //for AD Login
    public void createSession(wsad.types.BOEmployee i, wsad.types.BOUserLogin user) throws ParseException {
        //UserSession session1 =(UserSession)JSFUtils.resolveExpression("#{UserSession}");
        UserSession session1 =(UserSession)JSFUtils.resolveExpression("#{UserSession}");
        
     
        String s=i.getDateOfBirth().toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");

        java.util.Date date = sdf.parse(s);
        java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
        System.out.println("===================================================================");
System.out.println("dCode"+i.getDepartmentCode());
        System.out.println("dCode"+i.getConfirmationDate());
        System.out.println("dCode"+i.getDesignationCode());
        System.out.println("dCode"+i.getEmployeeCode());
        System.out.println("dCode"+i.getDepartmentCode());
        JSFUtils.storeOnSession("setPrivilege", i.getDepartmentCode());
        System.out.println("===================================================================");
     //System.out.println("DATE:"+timestamp);
     session1.setDob(timestamp);
      //session1.setAdminRole(adminrole);
        session1.setGender(i.getGender());
        session1.setUserFullname(i.getFullName());
        session1.setUsercode(i.getEmployeeCode());
        session1.setSessionKey(user.getSessionKey());
        
//        session1.setRole(Role);
//        session1.setDesignation(i.getDesignationName());
//        
//        System.out.println("\n\n\nAdmin Role:"+adminrole+"\n\n\n");
       //System.out.println("\nDEPARTMENT ID:"+i.getDepartmentID()+"\nDEPARTMENT NAME:"+i.getDepartmentName()+"\nDEPARTMENT CODE:"+i.getDepartmentCode()+"\n");
        session1.setEmail(i.getEmail());
        session1.setDeptCode(i.getDepartmentCode());
        session1.setEmpLocation(i.getParentOffice());
        session = session1;
        //System.out.println("Validating  " + session.getEmail() +
                          // session.getUserFullname()+"\n"+session.getDob()+"\n Gender: "+session.getGender());
        FacesContext fctx = FacesContext.getCurrentInstance();
        ExternalContext ectx = fctx.getExternalContext();
        HttpSession userSession = (HttpSession)ectx.getSession(true);
        userSession.setAttribute("empCode", i.getEmployeeCode());
        userSession.setAttribute("department", i.getDepartmentCode());
        userSession.setAttribute("empLocation", i.getParentOffice());
        
        System.out.println("====================5555555================================");
System.out.println("empLocation" + i.getParentOffice());
        System.out.println("empCode"+ i.getEmployeeCode());
        System.out.println("department"+ i.getDepartmentCode());
        System.out.println("====================================================");
        System.out.println("======================555555==============================");
        System.out.println("empLocation" + userSession.getAttribute("empCode"));
                System.out.println("empCode"+  userSession.getAttribute("department"));
                System.out.println("department"+  userSession.getAttribute("empLocation"));
        
        System.out.println("====================================================");

    }
    
    //for Mirror Dev Login
    public void createSession(ws.types.BOEmployee i, ws.types.BOUserLogin user) throws ParseException {
     //   UserSession session1 =(UserSession)JSFUtils.resolveExpression("#{UserSession}");
        
     UserSession session1= new UserSession(); 
        String s=i.getDateOfBirth().toString();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss");

        java.util.Date date = sdf.parse(s);
        java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());

    //        //System.out.println("DATE:"+timestamp);
        
        
        
        session1.setDob(timestamp);
        session1.setGender(i.getGender());
        session1.setUserFullname(i.getFullName());
        session1.setUsercode(i.getEmployeeCode());
        session1.setSessionKey(user.getSessionKey());
        
        
       //System.out.println("\nDEPARTMENT ID:"+i.getDepartmentID()+"\nDEPARTMENT NAME:"+i.getDepartmentName()+"\nDEPARTMENT CODE:"+i.getDepartmentCode()+"\n");
        session1.setEmail(i.getEmail());
        session1.setDeptCode(i.getDepartmentCode());
        session1.setEmpLocation(i.getParentOffice());
        session = session1;
        //System.out.println("Validating  " + session.getEmail() +
                          // session.getUserFullname()+"\n"+session.getDob()+"\n Gender: "+session.getGender());
        FacesContext fctx = FacesContext.getCurrentInstance();
        ExternalContext ectx = fctx.getExternalContext();
        HttpSession userSession = (HttpSession)ectx.getSession(true);
        userSession.setAttribute("empCode", i.getEmployeeCode());
        userSession.setAttribute("department", i.getDepartmentCode());
        userSession.setAttribute("empLocation", i.getParentOffice());

    }

    public void logoutHelper() {
        //System.out.println("\nLogout==================" + session.getEmail() +
                        //   session.getUserFullname()+"\n"+session.getDob()+"\n"+session.getGender());
        session.setDob(null);
        session.setGender(null);
        session.setUserFullname(null);
        session.setUsercode(null);
        session.setRole(null);
        session.setEmail(null);
        session.setDeptCode(null);
        session.setDob(null);
//        //System.out.println("\nLog1");
        session.setToken1(false);
        session.setToken2(false);
        session.setEmpLocation(null);
       // session.setAdminRole(null);
       doSessionInvalidate();
//        //System.out.println("\nLog3");

    }

    public void doSessionInvalidate() {
        ExternalContext extc =
            FacesContext.getCurrentInstance().getExternalContext();
        HttpSession sess = (HttpSession)extc.getSession(false);
        if (sess != null) {
//            //System.out.println("\nLog2");
            sess.invalidate();
        }
    
    }
    public void callRoleFinder(){
        if(session.getRole().endsWith("DH")){
            if(session.getToken1()){
                session.setToken1(false);
            }
            else{
                session.setToken1(true);
            }
            
        }
         if(session.getRole().endsWith("BUH")){
            if(session.getToken2()){
                session.setToken2(false);
            }
            else{
                session.setToken2(true);
            }
        }
        
    }


   
}


